<?php

	namespace app\common\middleware;

	use app\event\ucenter\AuthGroup as AuthGroupEvent;
	use app\event\ucenter\User as UserEvent;
	use app\model\ucenter\User as UserModel;
	use app\event\ucenter\IpPool as IpPoolEvent;
	use think\facade\Event;
	use think\Exception;
	use think\exception\HttpResponseException;
	use think\facade\Config;
	use think\facade\Cookie;
	use think\facade\Env;
	use think\facade\Lang;
	use think\facade\Log;
	use think\facade\Request;
	use think\facade\View;
	use think\Response;
	use think\response\Redirect;

	/**
	 * 访问环境检查，是否是微信或支付宝等
	 */
	class UserSafe
	{
		public function handle($request, \Closure $next)
		{
			// 安全检查
			$this->safeCheck($request, $request->user,$request->auth_module);
			return $next($request);
		}

		/**
		 * 检查权限.
		 * @param Request $request
		 * @param UserModel|null $user
		 * @param string $module
		 */
		protected function safeCheck($request, ?UserModel $user, string $module)
		{

			$ipEvent = new IpPoolEvent();
			$info = $ipEvent->info($request->ip());

//            Log::write($request->ip());
//            Log::write($info['data']->toArray());
			if ($info['code'] == 0) {
				$request->ipInfo = $info['data'];
//                dump($user);
//                dump($request->ipInfo->toArray());
			}
			// 防火墙
			Event::trigger('WafGet', ['user'=>$user,'module'=>$module]);
			// 检查IP地址访问
			if (in_array($request->ip(), explode(',', Config::get('setting.admin_allow_ip')))) {
				$response = Response::create(Lang::get('ip not allow'), 'html');
				throw new HttpResponseException($response);
			}

			if ($module == 'admin' && Env::get('safe.login') && $request->pathinfo() !== Env::get('safe.url')) {
				// 登录后台隐藏地址
				$html = '
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>安全入口校验失败</title>
</head>
<body>
    <h1>请使用正确的后台入口登录面板</h1>
    <p><b>错误原因：</b>系统已经开启了安全入口登录，系统都会随机一个8位字符的安全入口地址，如您没记录或不记得了，可以使用以下方式解决</p>
    <p><b>解决方法：</b>在登录系统后台或者通过FTP查看系统路由文件</p>
    <p>1.FTP查看面板入口：' . app()->getRootPath() . 'config' . DIRECTORY_SEPARATOR . 'safe.php内查看</p> 
    <p>2.FTP关闭安全入口：修改文件' . app()->getRootPath() . 'config' . DIRECTORY_SEPARATOR . 'safe.php内配置open=>0</p>
    <p>3.命令行查看入口：>php think safe url</p>
    <p>4.命令行修改入口：>php think safe url --value admin_address </p>
    <p>5.命令行关闭安全入口：>php think safe open --value 0 </p>
    <p style="color:red;">注意：【关闭安全入口】将使您的面板登录地址被直接暴露在互联网上，非常危险，请谨慎操作</p>
    <hr>
    <address>' . Config::get('setting.web_site_title') . '</address>
</body>
</html>';
				$response = Response::create($html, 'html');
				throw new HttpResponseException($response);
			}
		}


	}